<template>
  <div class="listening-practice">
    <div class="page-header">
      <!-- 重新设计的无图片播放器 -->
      <div class="mobile-player">
        <div class="player-background"></div>

        <div class="player-container">
          <div class="player-info">
            <div class="track-info">
              <div class="track-title">
                <van-icon name="music-o" class="title-icon" />
                {{ option.title || "听力练习" }}
              </div>

              <div class="track-status" v-if="duration > 0">
                <div class="status-badge" :class="{ playing: isPlaying }">
                  {{ isPlaying ? "播放中" : "已暂停" }}
                </div>
              </div>
            </div>

            <div class="progress-wrapper">
              <div class="time current">{{ formatTime(currentTime) }}</div>
              <div class="progress-bar-container" @click="seekAudio">
                <div class="progress-bg"></div>
                <div
                  class="progress-fill"
                  :style="{ width: `${progressPercentage}%` }"
                ></div>
                <div
                  class="progress-handle"
                  :style="{ left: `${progressPercentage}%` }"
                ></div>
              </div>
              <div class="time duration">{{ formatTime(duration) }}</div>
            </div>

            <div class="player-controls">
              <div class="controls-group">
                <van-icon
                  name="replay"
                  @click="restartAudio"
                  class="control-btn"
                />
                <van-icon
                  name="back"
                  @click="skipBackward"
                  class="control-btn"
                />
                <div class="play-button" @click="togglePlay">
                  <van-icon
                    :name="isPlaying ? 'pause-circle' : 'play-circle'"
                    class="play-icon"
                  />
                </div>
                <van-icon
                  name="forward"
                  @click="skipForward"
                  class="control-btn"
                />
                <div class="volume-control" @click="toggleMute">
                  <img
                    :src="isMuted ? volumn_off : volumn_on"
                    :alt="isMuted ? '静音' : '有声'"
                    class="volume-icon"
                    :class="{ muted: isMuted }"
                  />
                </div>
              </div>

              <div class="loading-indicator" v-show="isLoading">
                <van-loading type="spinner" size="20px" color="#4568dc" />
                <span>加载中...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 隐藏的原生音频元素 -->
        <audio
          ref="audioEl"
          preload="metadata"
          @timeupdate="onTimeUpdate"
          @loadedmetadata="onMetadataLoaded"
          @play="onPlay"
          @pause="onPause"
          @waiting="onWaiting"
          @canplay="onCanPlay"
          @ended="onEnded"
        >
          <source :src="option.src" type="audio/mpeg" />
        </audio>
      </div>

      <div class="progress-bar">
        <div class="progress-text">
          <van-icon name="medal-o" class="progress-icon" />
          <span>完成进度</span>
        </div>
        <van-progress
          :percentage="completionPercentage"
          :pivot-text="`${completionPercentage}%`"
          color="#7e57c2"
        />
      </div>
    </div>

    <div class="listen">
      <div class="section-header">
        <div class="section-badge">
          <span class="section-icon">A</span>
          <span>Section A</span>
        </div>
      </div>

      <div class="section-content">
        <div class="direction-card">
          <div class="direction-title">
            <van-icon name="guide-o" />
            <span>Directions</span>
          </div>
          <div class="direction-text">
            In this section, you will hear three news reports. At the end of
            each news report, you will hear two or three questions. Both the
            news report and the questions will be spoken only once. After you
            hear a question, you must choose the best answer from the four
            choices marked A), B), C) and D). Then mark the corresponding letter
            on Answer Sheet 1 with a single line through the centre.
          </div>
        </div>
      </div>

      <van-form>
        <div
          class="question-block"
          v-for="(item, index) in questions"
          :key="index"
        >
          <!-- Section headers with improved styling -->
          <div
            v-if="[0, 2, 4, 7, 11, 15, 18, 21].includes(index)"
            class="section-question"
          >
            <div class="question-header-content">
              <van-icon name="notes-o" class="question-icon" />
              <span v-if="index === 0"
                >Questions 1 and 2 are based on the news report you have just
                heard.</span
              >
              <span v-if="index === 2"
                >Questions 3 and 4 are based on the news report you have just
                heard.</span
              >
              <span v-if="index === 4"
                >Questions 5 to 7 are based on the news report you have just
                heard.</span
              >
              <span v-if="index === 7"
                >Questions 8 to 11 are based on the conversation you have just
                heard.</span
              >
              <span v-if="index === 11"
                >Questions 12 to 15 are based on the conversation you have just
                heard.</span
              >
              <span v-if="index === 15"
                >Questions 16 to 18 are based on the conversation you have just
                heard.</span
              >
              <span v-if="index === 18"
                >Questions 19 to 21 are based on the passage you have just
                heard.</span
              >
              <span v-if="index === 21"
                >Questions 22 to 25 are based on the passage you have just
                heard.</span
              >
            </div>
          </div>

          <!-- Section B and C headers -->
          <div v-if="index === 7" class="section-divider">
            <div class="section-badge section-b">
              <span class="section-icon">B</span>
              <span>Section B</span>
            </div>
            <div class="direction-card section-b-card">
              <div class="direction-title">
                <van-icon name="guide-o" />
                <span>Directions</span>
              </div>
              <div class="direction-text">
                In this section, you will hear two long conversations. At the
                end of each conversation, you will hear four questions. Both the
                conversation and the questions will be spoken only once. After
                you hear a question, you must choose the best answer from the
                four choices marked A), B), C) and D). Then mark the
                corresponding letter on Answer Sheet with a single line through
                the centre.
              </div>
            </div>
          </div>

          <div v-if="index === 15" class="section-divider">
            <div class="section-badge section-c">
              <span class="section-icon">C</span>
              <span>Section C</span>
            </div>
            <div class="direction-card section-c-card">
              <div class="direction-title">
                <van-icon name="guide-o" />
                <span>Directions</span>
              </div>
              <div class="direction-text">
                In this section, you will hear three passages. At the end of
                each passage, you hear three or four questions. Both the passage
                and the questions will be spoken only once. After you hear a
                question, you must choose the best answer from the four choices
                marked A), B), C) and D). Then mark the corresponding letter on
                Answer Sheet 1 with a single line through the centre.
              </div>
            </div>
          </div>

          <div class="question-item" :class="{ active: selected[index] }">
            <div class="question-header">
              <div class="number-badge">{{ index + 1 }}</div>
              <div class="question-status" v-if="selected[index]">
                <van-icon name="success" class="status-icon" />
                <span>已回答</span>
              </div>
            </div>

            <van-radio-group v-model="selected[index]" class="radio-group">
              <div class="options-grid">
                <div
                  class="option-card"
                  v-for="(option, optionIndex) in ['A', 'B', 'C', 'D']"
                  :key="option"
                  :class="{ 'selected-card': selected[index] === option }"
                  @click="selectOption(index, option)"
                >
                  <div class="option-content">
                    <div class="option-marker">
                      <span>{{ option }}</span>
                    </div>
                    <div class="option-text">
                      {{ item[`question${optionIndex + 1}`] }}
                    </div>
                    <van-radio
                      :name="option"
                      :disabled="disabledRadio"
                      class="option-radio"
                    />
                  </div>
                </div>
              </div>
            </van-radio-group>
          </div>
        </div>
      </van-form>

      <div class="submit-button">
        <van-button type="primary" block round size="large" @click="submit">
          <van-icon name="completed" />
          <span>提交答案</span>
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import volumn_on from "@/assets/volumn_on.png";
import volumn_off from "@/assets/volumn_off.png";
import { ref, onMounted, reactive, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showDialog, showToast } from "vant";
import audioApi from "@/api/audio/index";
import listenRecord from "@/api/listenRecord/index";
import host from "@/utils/host";
import listenImg from "@/assets/listen.jpg";

const route = useRoute();
const router = useRouter();
const option = reactive({
  src: "",
  title: "",
  coverImage: listenImg,
});

// 音频播放器状态
const audioEl = ref(null);
const isPlaying = ref(false);
const isLoading = ref(false);
const isMuted = ref(false);
const currentTime = ref(0);
const duration = ref(0);

// 计算进度百分比
const progressPercentage = computed(() => {
  if (!duration.value) return 0;
  return (currentTime.value / duration.value) * 100;
});

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) return "00:00";
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

// 播放器事件处理
const onTimeUpdate = () => {
  if (audioEl.value) {
    currentTime.value = audioEl.value.currentTime;
  }
};

const onMetadataLoaded = () => {
  if (audioEl.value) {
    duration.value = audioEl.value.duration;
  }
};

const onPlay = () => {
  isPlaying.value = true;
};

const onPause = () => {
  isPlaying.value = false;
};

const onWaiting = () => {
  isLoading.value = true;
};

const onCanPlay = () => {
  isLoading.value = false;
};

const onEnded = () => {
  isPlaying.value = false;
  currentTime.value = 0;
};

// 播放控制功能
const togglePlay = () => {
  if (!audioEl.value) return;

  if (isPlaying.value) {
    audioEl.value.pause();
  } else {
    audioEl.value.play().catch((error) => {
      console.error("播放失败:", error);
      showToast("音频播放失败，请重试");
    });
  }
};

const toggleMute = () => {
  if (!audioEl.value) return;

  audioEl.value.muted = !audioEl.value.muted;
  isMuted.value = audioEl.value.muted;
};

const restartAudio = () => {
  if (!audioEl.value) return;

  audioEl.value.currentTime = 0;
  if (!isPlaying.value) {
    togglePlay();
  }
};

const skipBackward = () => {
  if (!audioEl.value) return;

  audioEl.value.currentTime = Math.max(0, audioEl.value.currentTime - 10);
};

const skipForward = () => {
  if (!audioEl.value) return;

  audioEl.value.currentTime = Math.min(
    duration.value,
    audioEl.value.currentTime + 10
  );
};

const seekAudio = (event) => {
  if (!audioEl.value || !duration.value) return;

  const container = event.currentTarget;
  const rect = container.getBoundingClientRect();
  const offsetX = event.clientX - rect.left;
  const percentage = offsetX / rect.width;

  audioEl.value.currentTime = percentage * duration.value;
};

// 监听音频源变化
watch(
  () => option.src,
  (newSrc) => {
    if (newSrc && audioEl.value) {
      // 重置播放器状态
      currentTime.value = 0;
      duration.value = 0;
      isPlaying.value = false;

      // 等待DOM更新后加载新音频
      setTimeout(() => {
        audioEl.value.load();
      }, 0);
    }
  }
);

// 响应式数据
const disabledRadio = ref(false);
const audio = ref();
const questions = ref([]);
const selected = ref([]);

// 计算完成百分比
const completionPercentage = computed(() => {
  if (!selected.value.length) return 0;
  const answeredCount = selected.value.filter(Boolean).length;
  const totalCount = questions.value.length || 25;
  return Math.round((answeredCount / totalCount) * 100);
});

// 选择选项的方法
const selectOption = (index, option) => {
  if (!disabledRadio.value) {
    selected.value[index] = option;
  }
};

// 获取音频数据
const getAudio = async () => {
  if (route.query.id == null || route.query.id == undefined) {
    router.push("/learning/listening");
    showToast("获取音频数据失败");
    return;
  }
  try {
    const res = await audioApi.getById(route.query.id);
    audio.value = res.data;
    option.src = res.data.path;
    option.title = res.data.name;
    option.coverImage = listenImg;
    questions.value = JSON.parse(audio.value.questions);
    // 初始化选择数组
    selected.value = Array(questions.value.length).fill("");
  } catch (error) {
    showToast("获取音频数据失败");
  }
};

// 比较答案
const compareArray = () => {
  const arr = JSON.parse(audio.value.answers);
  let rightNum = 0;
  for (let index = 0; index < arr.length; index++) {
    if (arr[index] === selected.value[index]) {
      rightNum++;
    }
  }
  return rightNum * 4;
};

// 显示结果
const showResult = async (result) => {
  showToast({
    message: `您的得分是：${result}`,
    icon: "like-o",
    position: "middle",
    duration: 2000,
  });

  await listenRecord.updateScore(result, audio.value.id);
  setTimeout(() => {
    router.push({
      path: "/learning/listening",
    });
  }, 2000);
};

// 提交答案
const submit = async () => {
  disabledRadio.value = true;
  const selectedCount = selected.value.filter(Boolean).length;
  if (selectedCount < 25) {
    try {
      await showDialog({
        title: "提示",
        message: `您已完成 ${selectedCount}/25 题，还有未选择的题目，是否继续提交？`,
        confirmButtonText: "直接交卷",
        cancelButtonText: "检查一下",
        className: "custom-dialog",
      });
      const result = compareArray();
      showResult(result);
    } catch {
      showToast({
        message: "已取消提交",
        position: "bottom",
      });
      disabledRadio.value = false;
    }
  } else {
    const result = compareArray();
    showResult(result);
  }
};

// 生命周期钩子
onMounted(() => {
  getAudio();
});
</script>

<style scoped>
.listening-practice {
  background-color: #f5f9fe;
  min-height: 100vh;
  padding-bottom: 80px;
}

.page-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: #fff;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 自定义播放器样式 */
.mobile-player {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.player-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 120px;
  background: linear-gradient(135deg, #409eff, #70b3ff);
  z-index: 0;
}

.player-container {
  position: relative;
  z-index: 1;
  padding: 16px;
}

.player-info {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 18px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.track-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.track-title {
  font-size: 17px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  max-width: 70%;
}

.title-icon {
  color: #409eff;
}

.track-status {
  flex-shrink: 0;
}

.status-badge {
  font-size: 12px;
  background: #eee;
  color: #666;
  padding: 4px 10px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.status-badge.playing {
  background: rgba(64, 158, 255, 0.15);
  color: #409eff;
}

.progress-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.time {
  font-size: 12px;
  color: #666;
  width: 40px;
}

.current {
  text-align: left;
}

.duration {
  text-align: right;
}

.progress-bar-container {
  flex: 1;
  height: 6px;
  position: relative;
  cursor: pointer;
  border-radius: 3px;
  overflow: visible;
}

.progress-bg {
  position: absolute;
  height: 100%;
  width: 100%;
  background: #e1e1e1;
  border-radius: 3px;
}

.progress-fill {
  position: absolute;
  height: 100%;
  background: linear-gradient(to right, #409eff, #70b3ff);
  border-radius: 3px;
  transition: width 0.1s linear;
}

.progress-handle {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: white;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  border: 2px solid #409eff;
  z-index: 2;
}

.player-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.controls-group {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.control-btn {
  font-size: 22px;
  color: #409eff;
  padding: 8px;
  transition: all 0.2s ease;
}

.control-btn:active {
  transform: scale(0.95);
}

.control-btn.muted {
  color: #ff5252;
}

.play-button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #70b3ff);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.2s ease;
}

.play-button:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.play-icon {
  font-size: 30px;
  color: white;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #666;
  font-size: 13px;
  padding: 4px 0;
}

/* 隐藏原生音频元素 */
audio {
  display: none;
}

/* 进度条样式 */
.progress-bar {
  padding: 12px 16px;
  background: white;
}

.progress-text {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

.progress-icon {
  color: #409eff;
}

.listen {
  padding: 16px;
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
  max-width: 800px;
  margin: 0 auto;
}

.section-header {
  margin: 24px 0;
}

.section-badge {
  background: linear-gradient(135deg, #409eff, #70b3ff);
  color: white;
  padding: 10px 20px;
  border-radius: 30px;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.2);
  transition: transform 0.3s ease;
}

.section-badge:hover {
  transform: translateY(-2px);
}

.section-b {
  background: linear-gradient(135deg, #ff5f6d, #ffc371);
}

.section-c {
  background: linear-gradient(135deg, #11998e, #38ef7d);
}

.section-icon {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  width: 26px;
  height: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.section-divider {
  margin: 40px 0 30px;
  border-top: 1px dashed #ddd;
  padding-top: 30px;
}

.direction-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
  border-left: 4px solid #409eff;
}

.section-b-card {
  border-left: 4px solid #ff5f6d;
}

.section-c-card {
  border-left: 4px solid #11998e;
}

.direction-card:hover {
  transform: translateY(-3px);
}

.direction-title {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #409eff;
  font-weight: 600;
  margin-bottom: 15px;
  font-size: 17px;
}

.direction-text {
  color: #666;
  line-height: 1.7;
  font-size: 15px;
}

.section-question {
  margin: 30px 0 20px;
}

.question-header-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  color: #333;
  font-weight: 500;
  padding: 15px;
  background: rgba(64, 158, 255, 0.08);
  border-radius: 12px;
  line-height: 1.5;
}

.question-icon {
  color: #409eff;
  font-size: 18px;
  margin-top: 2px;
}

.question-block {
  margin: 30px 0;
}

.question-item {
  background: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.question-item.active {
  border-color: #409eff;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.number-badge {
  background: linear-gradient(135deg, #409eff, #70b3ff);
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.question-status {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #4caf50;
  font-size: 14px;
  padding: 5px 10px;
  background: rgba(76, 175, 80, 0.1);
  border-radius: 20px;
}

.status-icon {
  font-size: 14px;
}

.options-grid {
  display: grid;
  gap: 16px;
}

.option-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid #ebedf0;
  overflow: hidden;
  position: relative;
}

.option-card:hover {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.03);
}

.selected-card {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.05);
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.1);
}

.option-content {
  padding: 15px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.option-marker {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  min-width: 26px;
  border-radius: 50%;
  background: #f3f4f6;
  color: #409eff;
  font-weight: 600;
  margin-right: 12px;
  transition: all 0.3s ease;
}

.selected-card .option-marker {
  background: #409eff;
}

.option-text {
  flex: 1;
  font-size: 15px;
  line-height: 1.5;
  color: #444;
}

.selected-card .option-text {
  color: #333;
  font-weight: 500;
}

.option-radio {
  position: absolute;
  right: 15px;
}

:deep(.van-radio__icon) {
  font-size: 0;
  display: none;
}

.submit-button {
  margin: 40px auto;
  max-width: 500px;
  position: sticky;
  bottom: 24px;
}

:deep(.van-button--primary) {
  background: linear-gradient(135deg, #409eff, #70b3ff);
  border: none;
  height: 50px;
  font-size: 17px;
  font-weight: 600;
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

:deep(.van-button--primary:active) {
  background: linear-gradient(135deg, #3a8fe8, #65a8f0);
  transform: translateY(2px);
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.2);
}

:deep(.custom-dialog) {
  border-radius: 16px;
}

/* 添加动画 */
.question-item {
  animation: fadeIn 0.5s ease forwards;
  opacity: 0;
  transform: translateY(10px);
}

@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 添加响应式设计 */
@media (max-width: 768px) {
  .listen {
    padding: 12px;
  }

  .direction-card {
    padding: 16px;
  }

  .question-item {
    padding: 16px;
  }
}

/* 媒体查询 */
@media (max-width: 400px) {
  .player-info {
    padding: 15px;
  }

  .track-title {
    font-size: 15px;
  }

  .control-btn {
    font-size: 20px;
    padding: 6px;
  }

  .play-button {
    width: 45px;
    height: 45px;
  }

  .play-icon {
    font-size: 26px;
  }
}

/* 以下响应式调整针对更窄的手机屏幕 */
@media (max-width: 350px) {
  .player-container {
    flex-direction: column;
    padding: 10px;
    gap: 10px;
  }

  .player-info {
    width: 100%;
  }
}

/* 添加音量图标的过渡效果 */
.control-btn.van-icon {
  transition: all 0.3s ease;
}

/* 确保音量图标在切换时不会出现闪烁 */
.control-btn.van-icon::before {
  transition: opacity 0.3s ease;
}

/* 音量控制按钮样式 */
.volume-control {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.volume-control:active {
  transform: scale(0.95);
}

.volume-icon {
  width: 22px;
  height: 22px;
  object-fit: contain;
  transition: all 0.3s ease;
}

.volume-icon.muted {
  opacity: 0.7;
  filter: saturate(150%) hue-rotate(340deg);
}
</style>
